<template>
	<view>
		<view class="example">
			<form style="padding: 20rpx;">
				<view style="display: flex; padding: 30rpx 0rpx 30rpx 0rpx;border-bottom: 1px solid #f5f2f2;">
					<text>您的姓名：</text><input v-model="UserData.name" placeholder="请填写您的姓名"
						style="width: 450rpx; margin-left: 20rpx;" type="nickname"/>
				</view>
				<view style="display: flex; padding: 30rpx 0rpx 30rpx 0rpx;border-bottom: 1px solid #f5f2f2;">
					<text>您的手机：</text><input v-model="UserData.mobile" placeholder="请填写您的手机"
						style="width: 450rpx; margin-left: 20rpx;" type="number"/>
				</view>
				<view style="display: flex; padding: 30rpx 0rpx 30rpx 0rpx;">
					<text>身份证号：</text><input v-model="UserData.idNum" placeholder="请填写身份证号"
						style="width: 450rpx; margin-left: 20rpx;" type="idcard"/>
				</view>
			</form>
		</view>
		
		<view>
			<button type="primary" @click="setInfo" class="bind-buttom">提交</button>
		</view>
		<view style="color: #e09696; margin: 30rpx; text-align: center;font-size:26rpx;">
			请先完成“提交”操作，完成后可上传身份证照片
		</view>
		<!-- <view v-if="isAuthed"> -->
			<view class="form-container">
				<!-- 身份证国徽面照片 -->
				<view class="form-item">
					<view class="form-label">
						<text class="label-text">身份证国徽面照片</text>
						<text class="required">*</text>
					</view>
					<view class="upload-area" @tap="chooseImage('front')">
						<view v-if="!formData.frontImage" class="upload-placeholder">
							<image src="/static/upload.png" class="upload-icon" mode="aspectFit"></image>
							<text class="upload-text">点击上传身份证国徽面</text>
							<text class="upload-tip">请确保身份证信息清晰可见</text>
						</view>
						<view v-else class="upload-preview">
							<image :src="formData.frontImage" class="preview-image" mode="aspectFit"></image>
							<view class="preview-overlay">
								<text class="preview-text">点击重新上传</text>
							</view>
						</view>
					</view>
					<!-- 上传状态显示 -->
					<view v-if="frontUploadStatus" class="upload-status">
						<view v-if="frontUploadStatus === 'uploading'" class="status-loading">
							<text class="status-text">上传中...</text>
						</view>
						<view v-else class="status-result">
							<text class="status-text" :class="frontUploadStatus.includes('成功') ? 'status-success' : 'status-error'">
								国徽面上传结果：{{frontUploadStatus}}
							</text>
						</view>
					</view>
				</view>
				
				<!-- 身份证人像面照片 -->
				<view class="form-item">
					<view class="form-label">
						<text class="label-text">身份证人像面照片</text>
						<text class="required">*</text>
					</view>
					<view class="upload-area" @tap="chooseImage('back')">
						<view v-if="!formData.backImage" class="upload-placeholder">
							<image src="/static/upload.png" class="upload-icon" mode="aspectFit"></image>
							<text class="upload-text">点击上传身份证人像面</text>
							<text class="upload-tip">请确保身份证信息清晰可见</text>
						</view>
						<view v-else class="upload-preview">
							<image :src="formData.backImage" class="preview-image" mode="aspectFit"></image>
							<view class="preview-overlay">
								<text class="preview-text">点击重新上传</text>
							</view>
						</view>
					</view>
					<!-- 上传状态显示 -->
					<view v-if="backUploadStatus" class="upload-status">
						<view v-if="backUploadStatus === 'uploading'" class="status-loading">
							<text class="status-text">上传中...</text>
						</view>
						<view v-else class="status-result">
							<text class="status-text" :class="backUploadStatus.includes('成功') ? 'status-success' : 'status-error'">
								人像面上传结果：{{backUploadStatus}}
							</text>
						</view>
					</view>
				</view>
				
				<!-- 隐私说明 -->
				<view class="privacy-notice">
					<text class="notice-text">我们承诺将对您的身份证信息进行严格保密，本次仅用于身份验证，不会用于其他用途</text>
				</view>
			</view>
			
			<!-- 确认按钮 - 只有两张图片都上传成功才显示 v-if="canConfirm" -->
			<view class="confirm-section">
				<button class="confirm-btn" @tap="confirmUpload">
					确认
				</button>
			</view>
		</view>
		<!-- <view v-else style="color: #999; margin-top: 30rpx; text-align: center;">
			请先完成实名认证，认证后可上传身份证照片
		</view> -->
	<!-- </view> -->
</template>

<script>
	let App = getApp()
	export default {
		data() {
			return {
				UserData: {
					name: '',
					mobile: '',
					idNum: ''
				},
				accountId: '',
				flowId: '',
				isAuthed:true,
				formData: {
					idNumber: '',
					frontImage: '',
					backImage: ''
				},
				idNumberError: '',
				isSubmitting: false,
				submitResult: null,
				frontUploadStatus: '',
				backUploadStatus: ''
			}
		},
		computed: {
			canSubmit() {
				return this.formData.idNumber && 
					   this.formData.frontImage && 
					   this.formData.backImage && 
					   !this.idNumberError && 
					   !this.isSubmitting
			},
			canConfirm() {
				// 两张图片都上传成功才显示确认按钮
				return this.frontUploadStatus && 
					   this.backUploadStatus && 
					   this.frontUploadStatus !== 'uploading' && 
					   this.backUploadStatus !== 'uploading' &&
					   this.frontUploadStatus.includes('成功') && 
					   this.backUploadStatus.includes('成功')
			}
		},
		methods: {
			setInfo() {
				// 保存表单数据
				uni.setStorageSync('signUserForm', this.UserData)
				// 跳转认证
				let userinfo = uni.getStorageSync('userinfo');
				uni.showLoading({ title: '加载中' })
				this.$api.interfaceApi('createSignUser')({
					'realname': this.UserData.name,
					'mobile': this.UserData.mobile,
					'idNumber': this.UserData.idNum,
					'sys': App.globalData.sys,
				}).then(res => {
					if (res.code == 200) {
						uni.showToast({ title: res.msg, icon: 'success' })
						this.accountId = res.accountId
						this.flowId = res.flowId
						wx.navigateToMiniProgram({
							appId: 'wx1cf2708c2de46337',
							path: '/pages/index/index',
							extraData: {
								requestObj: {
									flowId: this.flowId,
									accountId: this.accountId,
									env: 'prod'
								},
								callbackObj: { url: 'wechat://back' }
							},
							success(res) { },
							fail(res) { },
							complete(res) { }
						})
					} else {
						setTimeout(() => {
							uni.showToast({ title: res.message, icon: 'none' })
						}, 500)
					}
					uni.hideLoading()
				})
			},
			goToUploadIDCard() {
				uni.navigateTo({
					url: '/pages/my/uploadIDCard'
				})
			},
			validateIdNumber() {
				const idNumber = this.formData.idNumber.trim()
				if (!idNumber) {
					this.idNumberError = '请输入身份证号码'
					return false
				}
				const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
				if (!idCardReg.test(idNumber)) {
					this.idNumberError = '请输入正确的身份证号码格式'
					return false
				}
				this.idNumberError = ''
				return true
			},
			chooseImage(type) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						uni.compressImage({
							src: tempFilePath,
							quality: 80,
							success: (compressRes) => {
								let filePath = compressRes.tempFilePath
								if (type === 'front') {
									this.formData.frontImage = filePath
									this.frontUploadStatus = 'uploading'
									this.uploadImageToServer(2, this.formData.idNumber || this.UserData.idNum, filePath, 'front')
								} else {
									this.formData.backImage = filePath
									this.backUploadStatus = 'uploading'
									this.uploadImageToServer(1, this.formData.idNumber || this.UserData.idNum, filePath, 'back')
								}
							},
							fail: () => {
								let filePath = tempFilePath
								if (type === 'front') {
									this.formData.frontImage = filePath
									this.frontUploadStatus = 'uploading'
									this.uploadImageToServer(2, this.formData.idNumber || this.UserData.idNum, filePath, 'front')
								} else {
									this.formData.backImage = filePath
									this.backUploadStatus = 'uploading'
									this.uploadImageToServer(1, this.formData.idNumber || this.UserData.idNum, filePath, 'back')
								}
							}
						})
					},
					fail: (err) => {
						console.error('选择图片失败:', err)
						let msg = '选择图片失败'
						if (err && err.errMsg) {
							if (err.errMsg.includes('auth deny') || err.errMsg.includes('permission')) {
								msg = '请在系统设置中授权微信访问相册和相机'
							} else if (err.errMsg.includes('cancel')) {
								msg = '已取消选择'
							}
						}
						uni.showToast({ title: msg, icon: 'none' })
					}
				})
			},
			// 将图片转换为base64格式
			fileToBase64(filePath) {
				return new Promise((resolve, reject) => {
					// 兼容路径格式
					let realPath = filePath;
					if (!/^wxfile:\/\//.test(filePath)) {
						// 不是小程序本地路径，尝试用 getImageInfo 获取
						uni.getImageInfo({
							src: filePath,
							success: (info) => {
								realPath = info.path;
								uni.getFileSystemManager().readFile({
									filePath: realPath,
									encoding: 'base64',
									success: (res) => {
										resolve(res.data)
									},
									fail: (err) => {
										console.error('readFile fail:', err, realPath)
										reject(new Error('图片转换失败（readFile）'))
									}
								})
							},
							fail: (err) => {
								console.error('getImageInfo fail:', err, filePath)
								reject(new Error('图片转换失败（getImageInfo）'))
							}
						})
					} else {
						uni.getFileSystemManager().readFile({
							filePath: realPath,
							encoding: 'base64',
							success: (res) => {
								resolve(res.data)
							},
							fail: (err) => {
								console.error('readFile fail:', err, realPath)
								reject(new Error('图片转换失败（readFile）'))
							}
						})
					}
				})
			},
			uploadImageToServer(type, idNumber, filePath, which) {
				this.fileToBase64(filePath).then(base64Data => {
					// ...拼接
					uni.getImageInfo({
						src: filePath,
						success: (info) => {
							let mimeType = 'image/jpeg';
							if (info.type === 'png') mimeType = 'image/png';
							if (info.type === 'jpg' || info.type === 'jpeg') mimeType = 'image/jpeg';
							const fileData = `data:${mimeType};base64,${base64Data}`;
							this.$api.interfaceApi('uploadFile')({
								sys: App.globalData.sys,
								type: type,
								idNumber: idNumber,
								file: fileData
							}).then(res => {
								if (res.code === 0) {
									uni.showToast({ title: res.message, icon: 'success', duration: 1200 })
									// if (which === 'front') this.frontUploadStatus = 'success'
									if (which === 'front') this.frontUploadStatus = res.message
									else this.backUploadStatus = res.message
								} else {
									uni.showToast({ title: res.message, icon: 'none', duration: 1200 })
									// if (which === 'front') this.frontUploadStatus = 'fail'
									if (which === 'front') this.frontUploadStatus = res.message
									else this.backUploadStatus = res.message
								}
							})
						},
						fail: (err) => {
							uni.showToast({ title: '图片信息获取失败', icon: 'none' })
							if (which === 'front') this.frontUploadStatus = 'fail'
							else this.backUploadStatus = 'fail'
						}
					})
				}).catch(err => {
					uni.showToast({ title: '图片处理失败', icon: 'none' })
					if (which === 'front') this.frontUploadStatus = 'fail'
					else this.backUploadStatus = 'fail'
				})
			},
			submitForm() {
				// 表单验证
				if (!this.validateIdNumber()) {
					return
				}
				// 提交表单
				this.isSubmitting = true
				setTimeout(() => {
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					})
				}, 1000)
				uni.navigateBack()
			},
			confirmUpload() {
				uni.showToast({
					title: '已确认，请等待审核',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}
		},
		onShow() {
			const saved = uni.getStorageSync('signUserForm')
			if (saved) this.UserData = saved
			// 检查认证状态（这里假设认证完成后会设置 signUserAuthed 标志）
			this.isAuthed = !!uni.getStorageSync('signUserAuthed')
			// 身份证号同步
			this.formData.idNumber = this.UserData.idNum
		}
	}
</script>

<style>
	.example {
			width: 690rpx;
			height: 360rpx;
			margin-top: 30rpx;
			margin-left: 30rpx;
			background-color: white;
			border-radius: 10px;
			display: flex;
	}
	.bind-buttom{
		width: 700rpx;
		height: 80rpx;
		margin-top: 30rpx;
		background-color: blue;
		border-radius: 40rpx;
	}
	/* 签约链接 */
	.register-link {
		margin-top: 16rpx;
		padding: 15rpx;
		text-align: center;
		
	}
	.register-text {
		font-size: 30rpx;
		color: #4a89dc;
		/* text-decoration: underline; */
	}

	/* 表单容器 */
.form-container {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
}

.form-item {
	margin-bottom: 40rpx;
}

.form-label {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.label-text {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.required {
	color: #ff4757;
	margin-left: 5rpx;
	font-size: 32rpx;
}

/* 输入框样式 */
.form-input {
	width: 100%;
	height: 80rpx;
	border: 2rpx solid #e8e8e8;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 30rpx;
	background-color: #fafafa;
	box-sizing: border-box;
}

.form-input:focus {
	border-color: #667eea;
	background-color: #fff;
}

.input-tip {
	font-size: 26rpx;
	color: #ff4757;
	margin-top: 10rpx;
	padding-left: 10rpx;
}

/* 上传区域样式 */
.upload-area {
	width: 100%;
	height: 300rpx;
	border: 2rpx dashed #ddd;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #fafafa;
	position: relative;
	overflow: hidden;
}

.upload-area:active {
	background-color: #f0f0f0;
}

.upload-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.upload-icon {
	width: 80rpx;
	height: 80rpx;
	margin-bottom: 20rpx;
	opacity: 0.6;
}

.upload-text {
	font-size: 30rpx;
	color: #666;
	margin-bottom: 10rpx;
}

.upload-tip {
	font-size: 24rpx;
	color: #999;
}

/* 预览样式 */
.upload-preview {
	width: 100%;
	height: 100%;
	position: relative;
}

.preview-image {
	width: 100%;
	height: 100%;
	border-radius: 12rpx;
}

.preview-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 12rpx;
	opacity: 0;
	transition: opacity 0.3s;
}

.upload-preview:active .preview-overlay {
	opacity: 1;
}

.preview-text {
	color: #fff;
	font-size: 28rpx;
}

/* 隐私说明 */
.privacy-notice {
	background-color: #f8f9fa;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-top: 20rpx;
}

.notice-text {
	font-size: 26rpx;
	color: #666;
	line-height: 1.5;
}

/* 提交按钮 */
.submit-section {
	padding: 0 20rpx;
	margin-top: 30rpx;
}

.submit-btn {
	width: 100%;
	height: 90rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	font-size: 32rpx;
	font-weight: 500;
	border-radius: 45rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 8rpx 20rpx rgba(102, 126, 234, 0.3);
	margin-bottom: 30rpx;
}

.submit-btn:active {
	transform: translateY(2rpx);
	box-shadow: 0 4rpx 10rpx rgba(102, 126, 234, 0.3);
}

.submit-btn-disabled {
	background: #ccc !important;
	box-shadow: none !important;
}

.result-section {
	margin-top: 30rpx;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 10rpx;
}

.result-card {
	padding: 20rpx;
	border-radius: 10rpx;
	background-color: #f8f9fa;
}

.result-icon {
	font-size: 40rpx;
	margin-bottom: 20rpx;
}

.result-content {
	text-align: center;
}

.result-title {
	font-size: 32rpx;
	font-weight: 500;
	margin-bottom: 10rpx;
}

.result-message {
	font-size: 28rpx;
	color: #666;
}

.icon-success {
	color: #4caf50;
}

.icon-error {
	color: #f44336;
}

/* 上传状态样式 */
.upload-status {
	margin-top: 20rpx;
	text-align: center;
}

.status-loading {
	width: 100rpx;
	height: 40rpx;
	border-radius: 20rpx;
	background-color: #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: center;
}

.status-result {
	margin-top: 10rpx;
}

.status-text {
	font-size: 26rpx;
	color: #666;
}

.status-success {
	color: #4caf50;
}

.status-error {
	color: #f44336;
}

/* 确认按钮样式 */
.confirm-section {
	padding: 20rpx;
	margin-top: 30rpx;
}

.confirm-btn {
	width: 100%;
	height: 90rpx;
	background: linear-gradient(135deg, #879dff 0%, #404af5 100%);
	color: #fff;
	font-size: 32rpx;
	font-weight: 500;
	border-radius: 45rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 8rpx 20rpx rgba(102, 126, 234, 0.3);
	margin-bottom: 30rpx;
}

.confirm-btn:active {
	transform: translateY(2rpx);
	box-shadow: 0 4rpx 10rpx rgba(102, 126, 234, 0.3);
}
</style>
